﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FaceDetectiveWindowsService
{
    public class AsyncFaceDeteiveSocketReceiveArgs : PluginService.Common.IRecieveArgs<byte[]>
    {
        #region 变量

        //System.Text.ASCIIEncoding _encoding = new ASCIIEncoding();
        System.Text.UTF8Encoding _encoding = new UTF8Encoding();

        private const int BUFFER_SIZE = 2048;
        const string MSGENDSIGN = "**";
        byte[] MSGENDSIGN_BYTES = null;

        List<byte> _cache = new List<byte>();
        byte[] _buffer = new byte[BUFFER_SIZE];
        byte[] _endBuf = new byte[MSGENDSIGN.Length];

        #endregion

        #region IRecieveArgs

        public byte[] CreateSendMsg(string msg)
        {
            if (msg != null)
            {
                var m1 = _encoding.GetBytes(msg);
                var m = new byte[m1.Length + MSGENDSIGN_BYTES.Length];
                Array.Copy(m1, m, m1.Length);
                Array.Copy(MSGENDSIGN_BYTES, 0, m, m1.Length, MSGENDSIGN_BYTES.Length);
                return m;
            }
            return null;
        }

        public void RefreshData(int readLen)
        {
            for (int i = 0; i < readLen; i++)
                _cache.Add(_buffer[i]);
        }

        public byte[] GetRecieveMessage()
        {
            try
            {
                int count = _cache.Count - _endBuf.Length;
                byte[] buf = new byte[count];
                _cache.CopyTo(0, buf, 0, count);
                _cache.Clear();
                //return create();
                return buf;
            }
            catch (Exception ex)
            {
                return null;
            }

            //object obj = SerializationFunc.Deserialize_Binary(buf);
            //AsyncSocketMessage msg = obj as AsyncSocketMessage;
            //if (msg == null)
            //    throw new Exception("接收数据不完整或传输的对象类型不能识别");
            //else
            //    return msg;
        }

        public int BufferSize
        {
            get { return BUFFER_SIZE; }
        }

        public byte[] Buffer
        {
            get { return _buffer; }
        }

        public bool RecieveEnd()
        {
            if (_cache.Count > MSGENDSIGN.Length)
            {
                _cache.CopyTo(_cache.Count - MSGENDSIGN.Length, _endBuf, 0, MSGENDSIGN.Length);
                string endStr = Encoding.UTF8.GetString(_endBuf);
                if (endStr == MSGENDSIGN)
                    return true;
                else
                    return false;
            }
            return false;
        }

        #endregion
    }
}
